package com.htandroid.htandroid.tools;

import android.os.Handler;
import android.os.Message;

import com.htandroid.htandroid.sys.InstorageURL;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * 访问WebService的工具类,
 * <p>
 * <p>
 * Created by lkp on 2015/12/9.
 */

public class ToolSOAP {

    // 含有3个线程的线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(3);

    public static void callService(final String methodName, final TreeMap<String, String> properties, final WebServiceCallBack webServiceCallBack) {
        callService(InstorageURL.SERVERURL, InstorageURL.NAME_SPACE, methodName, properties, webServiceCallBack);
    }

    /**
     * @param url                WebService服务器地址
     * @param namespace          命名空间
     * @param methodName         WebService的调用方法名
     * @param properties         WebService的参数
     * @param webServiceCallBack 返回结果回调接口
     */
    public static void callService(String url, final String namespace, final String methodName, final TreeMap<String, String> properties, final WebServiceCallBack webServiceCallBack) {
        // 创建HttpTransportSE对象，传递WebService服务器地址
        //url="http://"+url+"/htwebservice/services/HT";//新版webservice地址
        ToolLog.log(methodName + "======================callService");
        url = "http://" + url + BaseUrl_New;//旧版webservice地址
        final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
        // 创建SoapObject对象
        SoapObject soapObject = new SoapObject(namespace, methodName);
        // SoapObject添加参数
        if (properties != null) {
            ToolLog.log("======================properties:" + properties);
            for (int i = 0; i < properties.size(); i++) {
                Set keys1 = properties.keySet();

                String key = properties.keySet().toArray()[i].toString();

                soapObject.addProperty(key, properties.get(key));
            }
//            for (Iterator<Map.Entry<String, String>> it = properties.entrySet().iterator(); it.hasNext(); ) {
//                Map.Entry<String, String> entry = it.next();
//                soapObject.addProperty(entry.getKey(), entry.getValue());
//                Log.v("tag","ooooooooo"+entry.getKey()+ entry.getValue());
//            }
            ToolLog.log(soapObject.toString());
        }

        // 实例化SoapSerializationEnvelope，传入WebService的SOAP协议的版本号
        final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        // 设置是否调用的是.Net开发的WebService
//        soapEnvelope.setOutputSoapObject(soapObject);
        soapEnvelope.bodyOut = soapObject;
        soapEnvelope.dotNet = false;
        httpTransportSE.debug = false;

        // 用于子线程与主线程通信的Handler
        final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    webServiceCallBack.onSucced((SoapObject) msg.obj);
                } else {
                    webServiceCallBack.onFailure((String) msg.obj);
                }
            }
        };

        // 开启线程去访问WebService
        executorService.submit(new Runnable() {

            @Override
            public void run() {
                SoapObject resultSoapObject = null;
                Message mgs = mHandler.obtainMessage();
                try {
                    ToolLog.log("----------------------" + soapEnvelope.getResponse());
                    ToolLog.log("+++++++++++++++++++++++++++methodName:" + methodName);
                    httpTransportSE.call(namespace + methodName, soapEnvelope);

                    if (soapEnvelope.getResponse() != null) {
                        // 获取服务器响应返回的SoapObject
                        resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
                        ToolLog.log("======================resultSoapObject:" + resultSoapObject);
                    }
                    mgs.what = 0;
                    mgs.obj = resultSoapObject;

                } catch (Exception e) {
                    mgs.what = 1;
                    mgs.obj = e.getMessage();
                }

                // 将获取的消息利用Handler发送到主线程
                mHandler.sendMessage(mgs);
            }
        });
    }

    /**
     * WebService回调接口
     */
    public interface WebServiceCallBack {

        void onSucced(SoapObject result);

        void onFailure(String result);
    }
}